package com.example.myui.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.example.myui.R;

import java.util.ArrayList;

public class WebAdapter extends RecyclerView.Adapter<WebAdapter.Holder> {
    private static final int TYPE_HEAD = 1001;
    private static final int TYPE_OTHER = 1002;

    private Context mContext;
    private ArrayList<String> datas = null;

    public WebAdapter(Context context, ArrayList<String> strings) {
        this.mContext = context;
        this.datas = strings;
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        switch (viewType) {
            case TYPE_HEAD:
                view = LayoutInflater.from(mContext).inflate(R.layout.item_web, parent, false);
                break;
            case TYPE_OTHER:
                view = LayoutInflater.from(mContext).inflate(R.layout.item_text, parent, false);
                break;
        }
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(Holder holder, int position) {
        switch (holder.getItemViewType()) {
            case TYPE_HEAD:
                initWebView(holder.webview);
                break;
            case TYPE_OTHER:
                holder.textview.setText(datas.get(position));
                break;
        }
    }

    private void initWebView(WebView webView) {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webView.loadUrl("http://news.ifeng.com/a/20180313/56697892_0.shtml");
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_HEAD;
        } else {
            return TYPE_OTHER;
        }
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    public class Holder extends RecyclerView.ViewHolder {
        private final WebView webview;
        private final TextView textview;

        public Holder(View itemView) {
            super(itemView);
            webview = itemView.findViewById(R.id.webview1);
            textview = itemView.findViewById(R.id.tv_content);
        }
    }
}
